<template>
  <div class="company-user-list">
    <global-title title="角色管理列表"></global-title>
    <ul class="global-operation-list">
      <li class="global-operation-left">
        <ul class="global-filter-list">
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">角色名：</h2>
            <el-input
              placeholder="请输入"
              v-model="searchForm.keyword"
              clearable
            ></el-input>
          </li>
          <li class="global-filter-item global-filter-item-dateRange">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="开始时间"
              value-format="timestamp"
            ></el-date-picker>
            <div class="global-filter-item-dateRange-line"></div>
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              value-format="timestamp"
              placeholder="结束时间"
            ></el-date-picker>
          </li>
          <li class="global-filter-item">
            <el-button
              type="primary"
              class="global-filter-item-search"
              @click="rePosts"
              >搜索</el-button
            >
          </li>
        </ul>
      </li>
      <li class="global-operation-right">
        <el-button
          type="primary"
          class="global-operation-right-add"
          @click="addUser"
          v-if="operationList.includes('edit')"
          >新增</el-button
        >
        <!-- <el-button class="global-operation-right-export" v-if="operationList.includes('export')" @click="handleExport">导出</el-button> -->

<!--        <el-button-->
<!--          class="global-operation-right-export"-->
<!--          @click="handleDelAll"-->
<!--          v-if="operationList.includes('del')"-->
<!--          >删除</el-button-->
<!--        >-->
      </li>
    </ul>
    <div class="global-table-content">
      <div class="global-table">
        <el-table
          :data="dataList"
          :header-cell-style="{
            background: '#F6F7FA',
            color: '#333',
            height: '60px'
          }"
          v-loading="tableLoading"
                :row-style="{height: '0'}"
                :cell-style="{padding: '3px'}"
                max-height="500"
          ref="multipleTable"
          :default-sort="{ prop: 'createTime', order: 'descending' }"
          v-if="dataList && dataList.length > 0"
        >
          <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
          <el-table-column prop="id" label="序号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="roleName"
            label="名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="createTime"
            :formatter="formatterTime"
            label="创建时间"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="状态" show-overflow-tooltip>
            <template slot-scope="scope">
              <p class="global-table-status" v-if="scope.row.status === 1">
                已启用
              </p>
              <p class="global-table-status red" v-else>已禁用</p>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="68"
            v-if="operationList.length > 0"
          >
            <template slot-scope="scope">
              <p v-if="!operationList.includes('permissionEdit') && !operationList.includes('edit') && !operationList.includes('del')">无操作</p>
              <el-dropdown
                placement="bottom"
                @command="handleCommand($event, scope.row)"
                v-else
              >
                <span class="global-table-operation-btn">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    command="a"
                    v-if="operationList.includes('permissionEdit')"
                    >分配权限</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="b"
                    v-if="operationList.includes('edit')"
                    >修改</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="d"
                    v-if="operationList.includes('del')"
                    >删除</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="e"
                    v-if="
                      operationList.includes('del') && scope.row.status === 1
                    "
                    >禁用</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="f"
                    v-if="
                      operationList.includes('del') && scope.row.status === 3
                    "
                    >启用</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 暂无数据~ -->
        <div
          class="no-data"
          v-else
          style="height: calc(100vh - 130px - 80px);display: flex;align-items: center;justify-content: center;flex-direction: column"
        >
          <img style="width: 265px;height: 120px;margin-bottom: 32px" src="@/assets/images/tyNoData.png" alt="" />
          <div style="font-size: 16px;color: #A5A9B5">暂无数据~</div>
        </div>
      </div>
      <div class="global-page">
        <div class="global-page-left">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            :disabled="dataList.length === 0"
          ></el-checkbox>
          <!-- <el-button @click="handleDelAll" v-if="operationList.includes('del')" class="global-page-left-btn">删除</el-button> -->
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :current-page="pageNum"
          background
          layout="sizes, total, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :title="editDialogForm.title"
      :visible.sync="editDialog"
      :append-to-body="true"
      center
      width="700px"
      custom-class="global-form-dialog"
    >
      <el-form
        :model="editDialogForm"
        :rules="editDialogRules"
        ref="editDialogRules"
        label-width="120px"
        class="demo-ruleForm"
        autocomplete="off"
      >
        <el-form-item label="角色名称：" prop="roleName">
          <el-input
            v-model="editDialogForm.roleName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="global-form-dialog-btn">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="分配权限"
      :visible.sync="permissionDialog"
      :append-to-body="true"
      center
      width="500px"
      custom-class="permission-dialog"
    >
      <div class="permission-dialog-tree">
        <el-tree
          @check="clickNode"
          :data="treeList"
          ref="tree"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="idList"
          :props="defaultProps"
        >
        </el-tree>
      </div>
      <el-button
        class="permission-dialog-btn"
        type="primary"
        @click="getCheckedKeys"
        >保存</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import API from "@/api/apiCompanyUser";
import APICompany from "@/api/apiCompany";

export default {
  name: "CompanyUserList",
  props: {
    operationList: Array
  },
  data() {
    const validateRoleName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入角色名称"));
      } else if (
        !/^[a-zA-Z0-9_\u4e00-\u9fa5]{3,11}$/.test(
          this.editDialogForm.username
        )
      ) {
        callback(new Error("输入角色名称需限制在3-11位，中英文数字下划线字符"));
      } else {
        callback();
      }
    };
    return {
      inputType: "text", // 含有密码输入框时需要
      // 搜索条件
      searchForm: {
        sort: 2,
        keyword: null,
        startTime: null,
        endTime: null
      },
      // 表格相关
      isIndeterminate: false,
      checkAll: false,
      multipleSelection: [], // 多选
      editDialog: false, // 编辑弹窗
      // 编辑弹窗表单
      editDialogForm: {
        title: "新增用户",
        roleId: null,
        roleName: null
      },
      editDialogRules: {
        // 编辑弹窗表单验证
        roleId: [{ required: true, trigger: "blur" }],
        roleName: [
          { required: true, validator: validateRoleName, trigger: "blur" }
        ]
      },
      // 下拉框列表
      optionsData: {
        companyLoading: true,
        companyList: []
      },
      // 表格相关
      tableLoading: false,
      dataList: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      // 权限弹窗
      permissionDialog: false,
      permissionList: [],
      idList: [],
      treeList: [],
      currentId: null,
      defaultProps: {
        children: "children",
        label: "label"
      },
      roleId: null,
    };
  },
  activated() {
    this.init();
  },
  methods: {
    changeSort(e) {
      // e.order descending-降序-2 ascending-正序-1
      if (e.order === "descending") {
        this.searchForm.sort = 2;
      } else if (e.order === "ascending") {
        this.searchForm.sort = 1;
      } else {
        this.searchForm.sort = null;
      }
      this.rePosts();
    },
    // 全局初始化
    init() {
      // 搜索条件重置
      this.searchForm = {
        username: null,
        telephone: null,
        companyId: null
      };
      this.optionsData.companyLoading = true; // 初始化下拉框
      this.editDialog = false; // 初始化弹窗
      this.idList = [];
      this.permissionList = []; // 初始化权限列表
      this.rePosts();
    },
    // 防止密码自动输入
    changeInputType() {
      this.inputType = "password";
    },
    // 新增用户按钮
    addUser() {
      this.editDialogForm = {
        title: "新增角色",
        roleId: null,
        roleName: null
      };
      this.$nextTick(() => {
        this.$refs.editDialogRules.clearValidate();
      });
      this.editDialog = true;
    },
    // 表单操作项
    handleCommand(e, row) {
      console.log(row);
      if (e === "a") {
        this.getPermission(row.id);
      } else if (e === "b") {
        this.editDialog = true;
        this.editDialogForm = {
          title: "编辑角色",
          roleId: row.id,
          roleName: row.roleName
        };
      } else if (e === "c") {
        this.editDialog = true;
        this.editDialogForm = {
          title: "修改密码",
          userId: row.id
        };
      } else if (e === "d") {
        const ids = [row.id];
        this.handleStatus(ids, 2);
      } else if (e === "e") {
        const ids = [row.id];
        this.handleStatus(ids, 3);
      } else if (e === "f") {
        const ids = [row.id];
        this.handleStatus(ids, 1);
      }
    },
    // 表单选择
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(val);
    },
    // toastClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then(() => {
    //       done();
    //     })
    //     .catch(() => {});
    // },
    // 分页pageSize改变
    handleSizeChange(e) {
      this.pageSize = e;
      this.rePosts();
    },
    // 分页pageNum改变
    handleCurrentChange(e) {
      this.pageNum = e;
      this.getPost();
    },
    // 重新请求
    rePosts() {
      this.tableLoading = true;
      this.pageNum = 1;
      this.dataList = [];
      this.getPost();
    },
    // 表格列表
    getPost() {
      this.tableLoading = true;
      const params = {
        token: this.$store.state.token,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      if (this.searchForm.sort) {
        params.sort = this.searchForm.sort;
      }
      if (this.searchForm.startTime) {
        params.startTime = this.searchForm.startTime;
      }
      if (this.searchForm.keyword) {
        params.keyword = this.searchForm.keyword;
      }
      if (this.searchForm.endTime) {
        params.endTime = this.searchForm.endTime;
      }
      API.roleList(params).then(res => {
        if (res.key === 1000) {
          res = res.result;
          this.total = res.count;
          this.dataList = res.list;
          this.tableLoading = false;
        }
      });
    },
    // 获取下拉选项公司列表
    getCompany() {
      if (this.optionsData.companyLoading) {
        const params = {
          token: this.$store.state.token
        };
        APICompany.getCompanyList(params).then(res => {
          if (res.key === 1000) {
            res = res.result.list;
            this.optionsData.companyList = res;
            this.optionsData.companyLoading = false;
          }
        });
      }
    },
    // 编辑用户信息接口
    handleConfirm() {
      this.$refs.editDialogRules.validate(valid => {
        if (!valid) return;
        if (this.editDialogForm.title === "修改密码") {
          this.handleChangePassword();
        } else {
          this.handleEdit();
        }
      });
    },
    handleEdit() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        roleId: this.editDialogForm.roleId,
        roleName: this.editDialogForm.roleName
      };
      if (this.editDialogForm.userId) {
        params.userId = this.editDialogForm.userId;
      } else {
        params.password = this.editDialogForm.password;
      }
      API.upRole(params).then(res => {
        if (res.key === 1000) {
          if (this.editDialogForm.roleId) {
            this.$message({
              type: "success",
              message: "编辑成功"
            });
            this.getPost();
          } else {
            this.$message({
              type: "success",
              message: "新增成功"
            });
            this.rePosts();
          }
          this.editDialog = false;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    handleChangePassword() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        password: this.editDialogForm.password
      };
      API.changePassword(params).then(res => {
        if (res.key === 1000) {
          this.getPost();
          this.editDialog = false;
          this.$message({
            type: "success",
            message: "修改密码成功"
          });
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    // 编辑弹窗关闭
    handleEditDialogClose() {
      this.editDialog = false;
      this.$refs.editDialogRules.resetFields();
    },
    // 删除全部按钮
    handleDelAll() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const ids = this.multipleSelection.map(item => item.id);
        this.handleStatus(ids, 2);
      } else {
        this.$message({
          type: "warning",
          message: "请至少选择一项"
        });
      }
    },
    // 删除接口
    handleStatus(ids, status) {
      // status 1-启用 2-禁用 3-删除
      let title;
      if (status === 1) {
        title = "启用";
      } else if (status === 3) {
        title = "禁用";
      } else if (status === 2) {
        title = "删除";
      }
      this.$confirm("此操作将" + title + "该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$bus.$emit("show-loading", true);
          const params = {
            token: this.$store.state.token,
            status
          };
          if (status == 2){
            params.ids = ids.join(",");
            API.delRole(params).then(res => {
              if (res.key === 1000) {
                this.$message({
                  type: "success",
                  message: title + "成功"
                });
                if (status === 3) {
                  this.rePosts();
                } else {
                  this.getPost();
                }
              }
              this.$bus.$emit("show-loading", false);
            });
          }else{
            params.id = ids[0];
            params.type = status
            API.doDisenableRole(params).then(res => {
              if (res.key === 1000) {
                this.$message({
                  type: "success",
                  message: title + "成功"
                });
                if (status === 3) {
                  this.rePosts();
                } else {
                  this.getPost();
                }
              }
              this.$bus.$emit("show-loading", false);
            });
          }
        })
        // .catch(() => {
        //   this.$message({
        //     type: "info",
        //     message: "已取消" + title
        //   });
        // });
    },
    // 权限窗口关闭
    handlePermissionDialogClose() {
      this.permissionDialog = false;
    },
    formatterTime(row) {
      return this.$moment(row.createTime).format("YYYY-MM-DD HH:mm:ss");
    },
    getPermission(id) {
      this.roleId = id;
      this.idList = [];
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        roleId: id,
      };
      API.getRolePermissionList(params).then(res => {
        if (res.key === 1000) {
          res = res.result.list;
          this.permissionList = res;
          let treeList = [];
          const idList = [];
          res.forEach(firstItem => {
            const firstObj = {
              id: "x" + firstItem.id,
              label: firstItem.powerName
            };
            if (firstItem.list && firstItem.list.length > 0) {
              firstObj.children = [
                {
                  id: firstItem.id,
                  label: firstItem.powerName
                }
              ];
              if (firstItem.isChoose === 1) {
                idList.push(firstItem.id);
              }
              let bol = true;
              firstItem.list &&
                firstItem.list.forEach(secondItem => {
                  if (secondItem.buttonId) {
                    const secondObj = {
                      id: secondItem.buttonId,
                      label: secondItem.buttonName
                    };
                    firstObj.children.push(secondObj);
                  }
                  if (secondItem.isChooseButton === 1) {
                    idList.push(secondItem.buttonId);
                  } else if (secondItem.isChooseButton === 0) {
                    bol = false;
                  }
                });
              if (bol) {
                idList.push(firstItem.id);
              }
            }
            treeList.push(firstObj);
          });
          this.treeList = treeList;
          this.idList = idList;

          this.permissionDialog = true;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    getCheckedKeys() {
      const idList = this.$refs.tree.getCheckedKeys();
      const params = {
        token: this.$store.state.token,
        roleId: this.roleId,
        powerIds: JSON.stringify(idList.filter(item => item[0] !== "x"))
      };
      API.upRolePermission(params).then(res => {
        if (res.key === 1000) {
          this.permissionDialog = false;
          this.$message({
            type: "success",
            message: "分配成功"
          });
        }
      });
    },
    clickNode(node, { checkedKeys }) {
      let currentId = node.id;
      if (currentId[0] === "x") return; // 选中父级 无需操作
      let parentItem;
      this.treeList.some(firstItem => {
        if (!firstItem.children) return false;
        // if (firstItem.children[0] === currentId) return true;
        return firstItem.children.some(secondItem => {
          if (secondItem.id === currentId) {
            parentItem = firstItem;
            return true;
          }
          return false;
        });
      });
      if (parentItem) {
        if (parentItem.children[0].id === currentId) {
          const idList = checkedKeys;
          if (!checkedKeys.includes(currentId)) {
            parentItem.children.forEach(item => {
              let index = idList.indexOf(item.id);
              if (index > -1) {
                idList.splice(index, 1);
              }
            });
            this.$refs.tree.setCheckedKeys(idList);
          }
        } else {
          if (checkedKeys.includes(currentId)) {
            const idList = checkedKeys;
            console.log(idList.toString());
            idList.push(parentItem.children[0].id);
            console.log(idList.toString());
            this.$refs.tree.setCheckedKeys(idList);
          } else {
            const idList = checkedKeys;
            let bol = parentItem.children.some(item =>
              idList.includes(item.id)
            );
            if (!bol) {
              let index = idList.indexOf(parentItem.id);
              if (index > -1) {
                idList.splice(index, 1);
                this.$refs.tree.setCheckedKeys(idList);
              }
            }
          }
        }
      }
    },
    // 全选
    handleCheckAllChange() {
      this.$refs.multipleTable.toggleAllSelection();
    },
    //导出
    handleExport() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
      };
      if (this.searchForm.startTime) {
        params.startTime = this.searchForm.startTime;
      }
      if (this.searchForm.keyword) {
        params.keyword = this.searchForm.keyword;
      }
      if (this.searchForm.endTime) {
        params.endTime = this.searchForm.endTime;
      }
      API.getExportRoleList(params).then(res => {
        if (res) {
            const content = res.data
            const blob = new Blob([content])
            // 从response的headers中获取filename,
            // 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
            var contentDisposition = res.headers['content-disposition'];
            var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
            var result = patt.exec(contentDisposition);
            const fileName = decodeURI(result[1]);
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else { // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
        }
        this.$bus.$emit("show-loading", false);
      });
    },
  }
};
</script>

<style lang="sass" scoped>
.company-user-list
  @include container
  ::v-deep .permission-dialog
    .el-dialog__body
      display: flex
      align-items: center
      flex-direction: column
      padding: 30px 40px
      .permission-dialog-list
        max-height: 450px
        overflow-y: auto
        overflow-x: hidden
        margin-bottom: 40px
        .permission-dialog-item
          background: #f2f2f2
</style>
